package com.zmn.mcc.permit.client.policy.impl;

import com.zmn.mcc.permit.client.model.InterceptDecisionBO;
import com.zmn.mcc.permit.client.policy.interfaces.NoPermissionPolicy;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbookType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * 无权限时不处理属性，拦截方法返回null，在入参中查找HttpServletResponse,并写入空Excel对象
 *
 * @author hankangshuai
 * @since 2020/06/18
 */
public class WriteEmptyWorkBookPolicyImpl implements NoPermissionPolicy {

    @SneakyThrows
    @Override
    public InterceptDecisionBO processNoPermission(Object noPermissionParamObj, Field noPermissionField, Object[] targetAllParams) {
        Optional<HttpServletResponse> servletResponse = findHttpServletResponse(targetAllParams);
        if (!servletResponse.isPresent()) {
            throw new IllegalArgumentException("HttpServletResponse cannot be found in the parameters");
        }
        HttpServletResponse response = servletResponse.get();
        doEmptyExport(response);
        return InterceptDecisionBO.doIntercept(null);
    }

    /**
     * 创建空excel文件并导出
     *
     * @param response 响应对象
     */
    protected void doEmptyExport(HttpServletResponse response) throws IOException {
        XSSFWorkbook wb = new XSSFWorkbook(XSSFWorkbookType.XLSX);
        wb.createSheet("sheet1");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            response.reset();
            String fileName = URLEncoder.encode("export.xlsx", "utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            response.setContentType("application/msexcel");
            wb.write(outputStream);
        }
    }

    private Optional<HttpServletResponse> findHttpServletResponse(Object[] targetAllParams) {
        return Stream.of(targetAllParams)
                .filter(o -> o instanceof HttpServletResponse)
                .map(o -> (HttpServletResponse) o)
                .findFirst();
    }
}
